//login &&  register
const express = require('express')
const jwt = require('jsonwebtoken')
const User = require('../../models/User')
const bcrypt = require('bcrypt')
const gravatar = require('gravatar')
const passport = require('passport')
const router = express.Router()
//引入验证方法
const validateRegisterInput = require('../../validation/register')
const validateLoginInput = require('../../validation/login')

router.get('/test', (req, res) => {
    res.json({ msg: "login works" })
})

// register

router.post('/register', (req, res) => {
    // console.log(validateRegisterInput(req.body));

    let { errors, isValid } = validateRegisterInput(req.body)
    //判断isValid是否通过
    if (!isValid) {
        // console.log(errors); 

        return res.status(400).json(errors)
    }
    // 查询数据库中是否拥有邮箱
    User.findOne({ email: req.body.email })
        .then((user) => {
            if (user) {
                return res.status(400).json({ email: "邮箱已被注册" })
            } else {
                let avatar = gravatar.url('req.body.email', { s: '200', r: 'pg', d: 'mm' });
                const newUser = User({
                    name: req.body.name,
                    email: req.body.email,
                    avatar,
                    password: req.body.password
                })
                bcrypt.genSalt(10, function (err, salt) {
                    bcrypt.hash(newUser.password, salt, (err, hash) => {
                        // Store hash in your password DB.
                        if (err) throw err;
                        newUser.password = hash
                        newUser.save()
                            .then(user => res.json(user))
                            .catch(err => console.log(err)
                            )
                    });
                });


            }
        })


})

// login
router.post('/login', (req, res) => {
    const { errors, isValid } = validateLoginInput(req.body)
    //判断isValid是否通过
    if (!isValid) {
        return res.status(400).json(errors)
    }
    const email = req.body.email
    const password = req.body.password
    User.findOne({ email }).then(user => {
        if (!user) {
            return res.status(400).json({ email: "用户不存在" })
        }
        // 密码匹配
        bcrypt.compare(password, user.password)
            .then(isMatch => {
                if (isMatch) {
                    // console.log(1234531);
                    const rule = { id: user.id, name: user.name, avatar: user.avatar }
                    jwt.sign(rule, 'secret', { expiresIn: 3600 }, (err, token) => {
                        if (err) {
                            throw err
                        }
                        res.json({
                            success: true,
                            token: 'Bearer ' + token
                        })
                    })
                    // res.json({ msg: "登录成功" })

                } else {
                    return res.status(400).json({ password: "密码错误，请从新登录" })
                }

            })
    })
})

// token 验证、
router.get('/current', passport.authenticate('jwt', { session: false }), (req, res) => {
    res.json({
        id: req.user.id,
        name: req.user.name,
        email: req.user.email,
        avatar: req.user.avatar
    })


})

module.exports = router